import { CesiumIonDefaultAccessToken, TianDiTuToken } from './config'


const {
    Viewer,
    Ion,
    CesiumTerrainProvider,
    EllipsoidTerrainProvider,
    ImageryLayer,
    UrlTemplateImageryProvider,
    Rectangle,
    Color,
    Model,
    Entity,
    Math: CesiumMath,
    Transforms,
    Resource,
    Cartesian3,
    VertexFormat,
    Matrix4,
    Matrix3,
    SingleTileImageryProvider,
    GroundPrimitive,
    GeometryInstance,
    ImageMaterialProperty,
    PolygonGeometry,
    DistanceDisplayConditionGeometryInstanceAttribute,
    GeometryInstanceAttribute,
    ComponentDatatype,
    PolygonHierarchy,
    EllipsoidSurfaceAppearance,
    ScreenSpaceEventHandler,
    ScreenSpaceEventType,
    DirectionalLight,
    Material,
    Cartesian2,
    GeoJsonDataSource,
    Cesium3DTileset,
    Cartographic,
    ClassificationType,
    PrimitiveCollection,
    defined
} = Cesium
let miniLayer = null
export default class initCesium {
    constructor(el, option) {
        this.viewer = null
        this.initMap(el, option)
        this.addPlayer()
    };
    // 初始化地图设置
    initMap(el, option) {
        Ion.defaultAccessToken = CesiumIonDefaultAccessToken
        const viewer = new Viewer(el, {
            animation: false, //是否显示动画
            baseLayerPicker: false, //是否显示图层选择按钮
            fullscreenButton: false, //右下角的全屏按钮是否显示
            vrButton: false, //是否显示VR按钮
            geocoder: false, //右上角的搜索按钮是否显示
            homeButton: false, //是否显示有上面的回到首页图标
            infoBox: false, //是否显示属性信息窗口
            sceneModePicker: false, //是否显示二维三维切换按钮
            selectionIndicator: false, //当选中地球的上物体时，是否显示焦点图标
            timeline: false, //是否显示时间线
            navigationHelpButton: false, //是否显示操作帮助按钮
            navigationInstructionsInitiallyVisible: false, //操作帮助按钮是否在加载时就显示出来
            scene3DOnly: true, //如果为true，则每个几何实例仅以3D形式呈现以节省GPU内存
            shouldAnimate: true, //如果时钟默认情况下应尝试提前模拟时间，则为true，否则为false
            skyBox: false,
            sceneMode: Cesium.SceneMode.SCENE2D,
            mapMode2D: Cesium.MapMode2D.ROTATE,
            // imageryProvider: new ImageryLayer(
            //     new Cesium.WebMapTileServiceImageryProvider({
            //         url: `https://gatewayproxy-jcpt.mwr.cn/mdem30m/wmts100?k=qKa4F5YwHuxjT2EQl6BJoA%3D%3D`,
            //         layer: "m_dem30m",
            //         style: "default",
            //         tileMatrixSetID: "GoogleMapsCompatible_m_dem30m",
            //         format: "image/png",
            //         maximumLevel: 18,
            //         tileMatrixLabels: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"],
            //     }),
            // ).imageryProvider,
            // imageryProvider: new ImageryLayer(
            //     new UrlTemplateImageryProvider({
            //         url: `http://10.1.7.160:81/img_c/wmts`,
            //         //   subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
            //         maximumLevel: 17,
            //         credit: "TDTYX",
            //         // rectangle: Rectangle.fromDegrees(116.356344, 30.760149, 121.970943, 35.124159)
            //     }), { brightness: 1.2, contrast: 1.1 }
            // ).imageryProvider
            // imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
            //         // url: "http://t0.tianditu.gov.cn/img_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=3d3dd54815516d9ffed9667a79562535",
            //         url: 'http://10.1.7.160:81/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={TileMatrix}&TileCol={TileCol}&TileRow={TileRow}&REQUESTENCODING=KVP',
            //         format: 'tiles',
            //         tileMatrixSetID: 'c',
            //         tilingScheme: new Cesium.GeographicTilingScheme(),
            //         tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18'],
            //         layer: "tdtImgAnnoLayer",
            //         style: "default",
            //         show: false
            //     })
            imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
                // url: "http://t0.tianditu.gov.cn/img_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=3d3dd54815516d9ffed9667a79562535",
                url: 'https://gatewayproxy-jcpt.mwr.cn/ygyx2023/usmaps?request=gettile&tilesize=512&tilematrixset=l&format=webp&urls=%2Fmnt%2Fusdata%2F%E5%85%A8%E5%9B%BD%E4%B8%80%E5%BC%A0%E5%9B%BE%2F2023_2m%2F2023_2m.usrmp&k=qKa4F5YwHuxjT2EQl6BJoA%3D%3D',
                format: 'webp',
                tileMatrixSetID: 'l',
                tilingScheme: new Cesium.GeographicTilingScheme(),
                style: "default",
                show: false
            })

        });
        this.viewer = viewer
        viewer._cesiumWidget._creditContainer.style.display = "none"
        viewer.terrainProvider = Cesium.createWorldTerrain({
            requestWaterMask: false, // 开启水光效果
            requestVertexNormals: true // 开启地形光照
        });
        // viewer.scene.globe.depthTestAgainstTerrain = true // 地形遮挡
        viewer.scene.postProcessStages.fxaa.enabled = true;
        viewer.scene.debugShowFramesPerSecond = true // 帧率

        viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000000
        viewer.scene.screenSpaceCameraController.minimumZoomDistance = 4000
        viewer.scene.globe.baseColor = Color.fromCssColorString("#fff");
        // viewer.scene.primitives.add(new Cesium.createOsmBuildings())
        //判断是否支持图像渲染像素化处理
        if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
            var vtxf_dpr = window.devicePixelRatio
                // 适度降低分辨率
            while (vtxf_dpr >= 2.0) {
                vtxf_dpr /= 2.0
            }
            viewer.resolutionScale = vtxf_dpr
        }

        const baseLayer = viewer.imageryLayers.get(0)
        baseLayer.brightness = 1.2
        baseLayer.contrast = 1.1
        this.flyHome()
        const handler = new ScreenSpaceEventHandler(viewer.canvas);

        // 获取当前场景数据
        handler.setInputAction(
            debounce(function(movement) {
                // let pickRay = viewer.camera.getPickRay(movement.endPosition);
                // let ImageryLayerFeatures = viewer.imageryLayers.pickImageryLayers(pickRay, viewer.scene);
                // console.log(ImageryLayerFeatures, 'ImageryLayerFeaturesImageryLayerFeaturesImageryLayerFeaturesImageryLayerFeatures');

                // var pickedFeature = viewer.scene.pick(movement.endPosition);
                // var properties = pickedFeature.getPropertyNames();
                // for (var i = 0; i < properties.length; i++) {
                //     var propertyName = properties[i];
                //     var propertyValue = pickedFeature.getProperty(propertyName);

                //     // 打印要素属性
                //     console.log(propertyName + ": " + propertyValue);
                // }
                let obj = {}
                let pick = new Cartesian2(movement.endPosition.x, movement.endPosition.y)
                if (pick) {
                    let cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(pick), viewer.scene)
                    if (cartesian) {
                        //世界坐标转地理坐标（弧度）
                        let cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian)
                        if (cartographic) {
                            //海拔
                            let height = viewer.scene.globe.getHeight(cartographic)
                                //视角海拔高度
                            let he = Math.sqrt(
                                viewer.scene.camera.positionWC.x * viewer.scene.camera.positionWC.x +
                                viewer.scene.camera.positionWC.y * viewer.scene.camera.positionWC.y +
                                viewer.scene.camera.positionWC.z * viewer.scene.camera.positionWC.z
                            )
                            let he2 = Math.sqrt(cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z)
                                //地理坐标（弧度）转经纬度坐标
                            let point = [(cartographic.longitude / Math.PI) * 180, (cartographic.latitude / Math.PI) * 180]
                            if (!height) {
                                height = 0
                            }
                            if (!he) {
                                he = 0
                            }
                            if (!he2) {
                                he2 = 0
                            }
                            if (!point) {
                                point = [0, 0]
                            }
                            //俯仰角
                            let pitch = CesiumMath.toDegrees(viewer.scene.camera.pitch).toFixed(2)
                                //方向
                            let heading = CesiumMath.toDegrees(viewer.scene.camera.heading).toFixed(2)
                                // 级别
                            let tileRender = viewer.scene._globe._surface._tilesToRender
                            if (tileRender && tileRender.length > 0) {
                                obj.level = viewer.scene._globe._surface._tilesToRender[0]._level
                            }
                            obj.pitch = pitch
                            obj.dir = heading
                            obj.height = height.toFixed(2)
                            obj.lon = point[0].toFixed(6)
                            obj.lat = point[1].toFixed(6)
                            obj.vheihgt = (he - he2).toFixed(2)
                            option.baseInfoCb && option.baseInfoCb(obj)
                        }
                    }
                }
                let point = viewer.scene.pick(movement.endPosition)
                option.mouseMove(movement, point)
            }, 20),
            Cesium.ScreenSpaceEventType.MOUSE_MOVE
        );
        // 右击菜单
        handler.setInputAction(function(e) {
            let bool = store.state.panelStatus.isTooling // // 是否正在使用工具
            if (e.position !== undefined && !bool) {
                let div = document.querySelector(".menu-container")
                div.style.display = "block"
                div.style.left = e.position.x + "px"
                div.style.top = e.position.y + "px"
            }
            store.commit("panelStatus/TOGGLE_ISTOOLING", false)
        }, ScreenSpaceEventType.RIGHT_CLICK);
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
            // 左键点击事件
        handler.setInputAction(e => {
                try {
                    this.getScreenSpace(e)
                    const point = this.viewer.scene.pick(e.position)
                    option.leftClick && option.leftClick(e, point)
                } catch (error) {
                    console.error(error)
                }
            }, ScreenSpaceEventType.LEFT_CLICK)
            // 修改光照方向
        viewer.scene.light = new DirectionalLight({
            direction: new Cartesian3(0.6718879432029101, -0.7296064515958984, -0.1274402509735651),
            intensity: 3
        })
    };

    addPlayer() {
        // 30m
        // var superMapImageryLayer = new Cesium.WebMapTileServiceImageryProvider({
        //     url: `https://gatewayproxy-jcpt.mwr.cn/mdem30m/wmts100?k=qKa4F5YwHuxjT2EQl6BJoA%3D%3D`,
        //     layer: "m_dem30m",
        //     style: "default",
        //     tileMatrixSetID: "GoogleMapsCompatible_m_dem30m",
        //     format: "image/png",
        //     maximumLevel: 18,
        //     tileMatrixLabels: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"],
        // })
        // this.viewer.imageryLayers.addImageryProvider(superMapImageryLayer);


        var superMapImageryLayer = new Cesium.WebMapTileServiceImageryProvider({
            url: `https://gatewayproxy-jcpt.mwr.cn/rswbv/wmts100?k=qKa4F5YwHuxjT2EQl6BJoA%3D%3D&layer=rswb_v&style=default&tilematrixset=Custom_rswb_v&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={TileMatrix}&TileCol={TileCol}&TileRow={TileRow}`,
            layer: "rswb_v",
            style: "default",
            tileMatrixSetID: "Custom_rswb_v",
            format: "image/png",
            // maximumLevel: 19,
            // tileMatrixLabels: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
            tilingScheme: new Cesium.GeographicTilingScheme({
                numberOfLevelZeroTilesX: 2,
                numberOfLevelZeroTilesY: 1
            })
        })
        this.viewer.imageryLayers.addImageryProvider(superMapImageryLayer);


        var superMapImageryLayer = new Cesium.WebMapTileServiceImageryProvider({
            url: `https://gatewayproxy-jcpt.mwr.cn/sx_r/wmts100?k=qKa4F5YwHuxjT2EQl6BJoA%3D%3D&layer=sx_r&style=default&tilematrixset=Custom_sx_r&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={TileMatrix}&TileCol={TileCol}&TileRow={TileRow}`,
            layer: "sx_r",
            style: "default",
            tileMatrixSetID: "Custom_sx_r",
            format: "image/png",
            // maximumLevel: 19,
            // tileMatrixLabels: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
            tilingScheme: new Cesium.GeographicTilingScheme({
                numberOfLevelZeroTilesX: 2,
                numberOfLevelZeroTilesY: 1
            })
        })
        this.viewer.imageryLayers.addImageryProvider(superMapImageryLayer);

    };
    //   初始化
    flyHome() {
        let lonlat = JSON.parse(localStorage.getItem('areaLabels'))[0];
        let height = localStorage.getItem('scaleLevel') * 1.5
        this.gotoEntities(...lonlat, 0, -90, height, 0.1)
            // this.viewer.camera.flyTo({
            //     destination: Cesium.Cartesian3.fromDegrees(19.2493, 4.3331, 4995455.8920),
            //     orientation: {
            //         heading: 6.2832,
            //         pitch: -1.5708,
            //         roll: 0.00
            //     },
            //     duration: 1
            // })
    };
    gotoEntities(lon, lat, heading = 8.0, pitch = -30.2, range = 2000.0, duration = 2) {
        const boundingSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(lon, lat), 500)
            // const heading = Cesium.Math.toRadians(heading)
            // const pitch = Cesium.Math.toRadians(pitch)
            // const range = range
        this.viewer.camera.flyToBoundingSphere(boundingSphere, {
            offset: new Cesium.HeadingPitchRange(Cesium.Math.toRadians(heading), Cesium.Math.toRadians(pitch), range),
            duration: duration
        })
    };
    // 获取当前相机经纬度信息，高度，方向角，俯仰角等信息
    getScreenSpace(e) {
        const point = this.viewer.scene.camera.position
        var cartesian33 = new Cartesian3(point.x, point.y, point.z)
        var cartographic = Cartographic.fromCartesian(cartesian33)
        var lat = CesiumMath.toDegrees(cartographic.latitude).toFixed(4)
        var lng = CesiumMath.toDegrees(cartographic.longitude).toFixed(4)
            // var alt = cartographic.height.toFixed(4)
            // var heading = this.viewer.scene.camera.heading.toFixed(4)
            // var pitch = this.viewer.scene.camera.pitch.toFixed(4)
            // var roll = this.viewer.scene.camera.roll.toFixed(4)
        var zoomLevel = this.viewer.scene.camera.positionCartographic.height;

        let level = this.viewer.scene._globe._surface._tilesToRender[0]._level
        console.log(`${lng},${lat}`, zoomLevel, level)
            // return { lng, lat, alt, heading, pitch, roll }
    };
    //删除entities通过name
    removeEntities(name) {
        for (let i = this.viewer.entities.values.length - 1; i > -1; i--) {
            const item = this.viewer.entities.values[i]
            if (item.name && item.name == name) {
                this.viewer.entities.remove(item)
            }
        }
    };

    // export function mouseZoom(viewer, fn) {
    //     //鼠标位置信息
    //     let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    //     // 鼠标中间滚动
    //     handler.setInputAction((event) => {
    //       let tileRender = viewer.scene._globe._surface._tilesToRender
    //       if (tileRender && tileRender.length > 0) {
    //         let level = viewer.scene._globe._surface._tilesToRender[0]._level
    //         // console.log('level = ' + level);
    //         fn && fn(level)
    //       }
    //     }, Cesium.ScreenSpaceEventType.WHEEL)
    //   }

    /**
     * 添加底图
     * @param {String} type
     */
    addUnderlay(type) {
        if (type == "TDTYX") {
            // 天地图影像
            this.viewer.imageryLayers.addImageryProvider(
                new Cesium.WebMapTileServiceImageryProvider({
                    url: "http://t{s}.tianditu.gov.cn/img_w/wmts?tk=" + TianDiTuToken,
                    layer: "img",
                    credit: "TDTYX",
                    tileMatrixSetID: "w",
                    format: "tiles",
                    maximumLevel: 18,
                    subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
                    rectangle: Cesium.Rectangle.fromDegrees(116.356344, 30.760149, 121.970943, 35.124159)
                })
            )
        } else if (type == "TDTSL") {
            // 天地图矢量
            this.viewer.imageryLayers.addImageryProvider(
                new Cesium.WebMapTileServiceImageryProvider({
                    // url: 'http://t0.tianditu.gov.cn/img_w/wmts?tk=73d2105c3710ca08d2ad36daaf4c4a87',
                    url: "http://t{s}.tianditu.gov.cn/vec_w/wmts?tk=" + TianDiTuToken,
                    layer: "vec",
                    credit: "TDTSL",
                    style: "default",
                    tileMatrixSetID: "w",
                    format: "tiles",
                    subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
                    maximumLevel: 18
                })
            )
        }
    };


    // 多维数组转一维数组
    flatten(arr) {
        return [].concat(...arr.map(x => (Array.isArray(x) ? this.flatten(x) : x)))
    }
}
// fnagdou
const debounce = function(func, wait) {
    let timeout = null
    return function() {
        let context = this,
            args = arguments
        clearTimeout(timeout)
        timeout = setTimeout(function() {
            func.apply(context, args)
        }, wait)
    }
}